<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8"/>
    <link rel="stylesheet" href="/febs/vue/element-ui-index.css"/>
    <link rel="stylesheet" href="/febs/vue/vxe-table-style.css"/>
    <link rel="stylesheet" href="/febs/vue/font-awesome/css/font-awesome.min.css"/>
    <script src="/febs/vue/vue.js"></script>
    <script src="/febs/vue/axios.min.js"></script>
    <script src="/febs/vue/element-ui-index.js"></script>
    <script src="/febs/vue/xe-utils.js"></script>
    <script src="/febs/vue/vxe-table.js"></script>
    <script src="/febs/vue/sortable.js"></script>
</head>

<body>
<div id="app" class="layui-fluid w-app">
    <div class="text-left" style="margin-bottom: 20px">
        <span style="font-weight: 600">流程名称：{{nameT}}</span>
        <span class="wmarginleft30">流程编号：{{basestdNo}} </span>
    </div>
    <!-- <vxe-toolbar>
  <template #buttons>
    <vxe-button style="float:right" icon="fa fa-plus" @click="insertEvent(-1)">新增一行</vxe-button>
  </template>
</vxe-toolbar> -->
    <vxe-table border show-overflow keep-source resizable ref="xTable" max-height="480" :data="tableData" row-key
               :edit-config="{trigger: 'click', mode: 'row', icon: 'fa fa-pencil', showStatus: true}"
               :edit-rules="validRules" :scroll-y="{enabled: false}">
        <vxe-table-column class-name="dragable" field="flowSeq" width="80" title="序号"></vxe-table-column>
        <vxe-table-column field="nameT" title="流程名称" :edit-render="{name: 'input', defaultValue: '',}"
                          min-width="150">
        </vxe-table-column>
        <vxe-table-column field="nameS" title="签核人员" :edit-render="{name: 'input'}" min-width="120">
            <template #edit="{ row }">
                <vxe-pulldown ref="xPulldown" transfer>
                    <template #default>
                        <vxe-input v-model="row.tempNameS" class="custom-input" placeholder="请选择"
                                   @focus="clickDropdown(row)" @search-click="searchByName(row)"
                                   @keyup="filterNameS(row)" type="search" @blur="setNameS(row)"></vxe-input>
                    </template>
                    <template #dropdown>
                        <vxe-list ref="xList" height="200" style="padding: 2px;border: 1px #ddd solid;" :data="downList"
                                  :loading="!downList.length"
                                  auto-resize>
                            <template #default="{ items }">
                                <div class="nameS-pulldown" v-for="item in items" :key="item.chkUser"
                                     @click="selectHandle(item, row)">
                                    <div style="display: flex;justify-content: space-between;">
                                        <span>{{ item.nameS }}</span>
                                        <span>{{ item.chkUser }}</span>
                                    </div>
                                    <div
                                            style="display: flex;justify-content: space-between;color:#bbb;font-size: 12px;position: relative;top: -.3em;">
                                        <span>{{ orgMap[item.orgId] }}</span>
                                        <span>{{ item.deptName }}</span>
                                    </div>
                                </div>
                            </template>
                        </vxe-list>
                    </template>
                </vxe-pulldown>
            </template>
        </vxe-table-column>
        <vxe-table-column field="chkUser" title="签核帐号" :edit-render="{name: 'input'}"
                          min-width="100">
            <template #edit="{ row }">
                <vxe-input v-model="row.chkUser" placeholder="请选择"></vxe-input>
            </template>
        </vxe-table-column>
        <vxe-table-column title="操作" width="80" show-overflow>
            <template #default="{ row, rowIndex }">
                <a>
                    <i class="layui-icon febs-edit-area febs-red" @click="getRemoveEvent(rowIndex)">&#xe7f9;</i>
                </a>
            </template>
        </vxe-table-column>
    </vxe-table>
    <button type="button"
            style="border-style: dashed; border-radius: 0; border-top: none; border-right-width: 2px; margin-bottom: 20px"
            class="layui-btn layui-btn-primary layui-border-blue layui-btn-fluid layui-btn-lg" @click="insertEvent(-1)">
        <i class="layui-icon" style="position: relative; top: -2px">&#xe624;</i>新增一行
    </button>
    <vxe-toolbar>
        <template #buttons>
            <vxe-button style="float: right" icon="fa fa-save" @click="verificationRequired" class="submit"
                        status="success" :loading="loading">保存
            </vxe-button>
        </template>
    </vxe-toolbar>
</div>
</body>
<script>
    new Vue({
        el: "#app",
        data() {
            //自定义校验方法
            // const validatePass = (rule, value, callback) => {
            //   if (value == "" || value == null) {
            //     callback(new Error("good"));
            //   } else {
            //     callback();
            // }
            // };
            return {
                timer:null,
                basestdNo: "",
                nameT: "",
                orgId: null,
                defaultTableData: [],
                tableData: [],
                removeData: [],
                signList: [{
                    label: "Y",
                    value: "Y"
                }, {
                    label: "N",
                    value: "N"
                },],
                isRequired: false,
                validRules: {
                    flowSeq: [{
                        required: true,
                        message: "必须填写数字"
                    }],
                    nameT: [{
                        required: true,
                        message: "必须填写"
                    }],
                    upSerialNumber: [{
                        required: true,
                        message: "必须填写数字"
                    }],
                    chkUser: [{
                        required: true,
                        message: "必须填写"
                    }],
                    nameS: [{
                        required: true,
                        message: "必须填写"
                    }],
                    isFirst: [{
                        required: true,
                        message: "必须选择"
                    }],
                    isLast: [{
                        required: true,
                        message: "必须选择"
                    }],
                },
                loading: false,
                allEmployee: [],
                downList: [],
                orgMap: {}
            };
        },
        created() {
            (Vue.prototype.$XModal = VXETable.modal), (this.basestdNo = JSON.parse(sessionStorage.baseFlowData).basestdNo);
            this.nameT = JSON.parse(sessionStorage.baseFlowData).nameT;
            this.orgId = JSON.parse(sessionStorage.baseFlowData).orgId;
            this.search();
            this.zoomTable();
            // this.allEmployee = JSON.parse(sessionStorage.allEmployee);
            // this.downList = this.allEmployee;
            const orgList = JSON.parse(sessionStorage.OrgList);
            orgList.forEach(item => {
                if (item.orgId && item.shortnmT) {
                    this.orgMap[item.orgId] = item.shortnmT;
                }
            });
        },
        mounted() {
            const that = this;
            Sortable.create(this.$refs.xTable.$el.querySelector("tbody"), {
                handle: ".dragable",
                // onEnd: ({ newIndex, oldIndex }) => {
                onEnd: function ({
                                     newIndex,
                                     oldIndex
                                 }) {
                    const tableData = that.tableData;
                    const xTable = that.$refs.xTable;
                    const currRow = tableData.splice(oldIndex, 1)[0];
                    tableData.splice(newIndex, 0, currRow);
                    // tableData.forEach((item, index) => {
                    tableData.forEach(function (item, index) {
                        item.flowSeq = index + 1;
                        item.upFlow = index;
                        item.isFirst = index === 0 ? "Y" : "N";
                        item.isLast = index === tableData.length - 1 ? "Y" : "N";
                    });
                    xTable.loadData(tableData);
                },
            });
        },
        methods: {
            selectHandle(item, row) {
                const $pulldown = this.$refs.xPulldown;
                this.$set(row, 'tempNameS', item.nameS);
                this.$set(row, 'nameS', item.nameS);
                this.$set(row, 'chkUser', item.chkUser);
                this.$set(row, 'deptName', item.deptName);
                if ($pulldown) {
                    $pulldown.hidePanel();
                }
            },
            clickDropdown(row) {
                const $pulldown = this.$refs.xPulldown;
                this.$set(row, 'tempNameS', row.nameS);
                // // const allEmployee = JSON.parse(sessionStorage.allEmployee) || [];
                // // if (!this.allEmployee.length && allEmployee.length) {
                // // this.allEmployee = JSON.parse(sessionStorage.allEmployee);
                // //     this.$refs.xList.reloadData(this.downList);
                // // }
                // if (row.nameS) {
                //     this.downList = this.allEmployee.filter(item => this.filterHandle(item, row.tempNameS));
                // } else {
                //     this.downList = this.allEmployee;
                // }

            },
            filterNameS(row) {
                if (!row.tempNameS) {
                    const $pulldown = this.$refs.xPulldown;
                    $pulldown.hidePanel()
                    this.downList=[]
                    return
                }
                if (this.timer) {
                    clearTimeout(this.timer)
                    this.timer = null
                }
                this.timer = setTimeout(() => this.searchUser(row.tempNameS), 300)
            },
            searchUser(value) {
                axios
                    .get(`baseflow/getEmpNO?name=${value}`).then(res => {
                    // this.allEmployee = res
                    this.downList = res.data.data
                    const $pulldown = this.$refs.xPulldown;
                    $pulldown.showPanel();
                })

            },
            setNameS(row) {
                if (row.tempNameS) {
                    this.$set(row, 'nameS', row.tempNameS);
                }

            },
            filterHandle(item, query) {
                if (query) {
                    return item.nameS.includes(query) || (item.deptName || '').includes(query) || (item.chkUser || '').toString().includes(query);
                }
                return true
            },
            search() {
                const that = this;
                axios
                    .get("/baseStd/baseStdDetails", {
                        params: {
                            basestdNo: JSON.parse(sessionStorage.baseFlowData).basestdNo,
                            orgId: JSON.parse(sessionStorage.baseFlowData).orgId,
                        },
                    })
                    .then(function (response) {
                        const tableData = response.data.data;
                        // tableData.forEach((item, index) => {
                        tableData.forEach(function (item, index) {
                            item.oldFlowSeq = item.flowSeq;
                            item.oldIsFirst = item.isFirst;
                            item.oldIsLast = item.isLast;
                            if (item.upFlow) {
                                item.upFlow = parseInt(item.upFlow);
                                item.oldUpFlow = item.upFlow;
                            }
                            if (!item.oldChkUser) {
                                item.oldChkUser = item.chkUser;
                            }
                            if (!item.oldNameS) {
                                item.oldNameS = item.nameS;
                                item.tempNameS = item.nameS;
                            }
                            if (!item.oldNameT) {
                                item.oldNameT = item.nameT;
                            }
                            item.defaultIndex = index;
                        });
                        that.tableData = tableData;
                        that.defaultTableData = JSON.parse(JSON.stringify(tableData));
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            async insertEvent(row) {
                const tableData = this.tableData;
                const $table = this.$refs.xTable;
                const record = {
                    basestdNo: this.basestdNo,
                    orgId: this.orgId,
                    nameE: this.nameT,
                    flowSeq: tableData.length + 1,
                    upFlow: tableData.length,
                    isFirst: "N",
                    isLast: "Y",
                };
                // tableData.forEach((item, index) => {
                tableData.forEach(function (item, index) {
                    item.isFirst = "N";
                    item.isLast = "N";
                    if (index === 0) {
                        item.isFirst = "Y";
                    }
                });
                tableData.push(record);
                $table.updateData(tableData);
                await $table.setActiveCell(record, "name");
            },
            //获取新增
            getInsertEvent() {
                const $table = this.$refs.xTable;
                const insertRecords = $table.getInsertRecords();
                this.$XModal.alert(insertRecords.length);
            },
            //获取删除
            getRemoveEvent(index) {
                const $table = this.$refs.xTable;
                const tableData = this.tableData;
                const removeRow = {
                    ...tableData.splice(index, 1)[0]
                };
                removeRow.flowSeq = removeRow.oldFlowSeq;
                removeRow.upFlow = removeRow.oldUpFlow;
                this.removeData.push(removeRow);
                // tableData.forEach((item, i, arr) => {
                tableData.forEach(function (item, i, arr) {
                    item.flowSeq = i + 1;
                    item.upFlow = i;
                    item.isFirst = i === 0 ? "Y" : "N";
                    item.isLast = i === arr.length - 1 ? "Y" : "N";
                });
                $table.updateData(tableData);
            },
            //获取修改
            getUpdateEvent() {
                const $table = this.$refs.xTable;
                const updateRecords = $table.getUpdateRecords();
                console.log("获取修改", updateRecords);
                this.$XModal.alert(updateRecords.length);
            },
            getSelectionEvent() {
                const $table = this.$refs.xTable;
                const selectRecords = $table.getCheckboxRecords();
                this.$XModal.alert(selectRecords.length);
            },
            //校验必填项
            verificationRequired() {
                const $table = this.$refs.xTable;
                const $tableData = $table.getTableData().tableData;
                const that = this;
                if ($tableData.length > 0) {
                    $tableData.forEach(function (item) {
                        if (!item.flowSeq || !item.nameT || !item.chkUser || !item.nameS) {
                            that.isRequired = true;
                            return false;
                        } else {
                            that.isRequired = false;
                        }
                    });
                    // this.$nextTick(() => {
                    that.$nextTick(function () {
                        if (that.isRequired) {
                            that.$XModal.alert("必填项有空，不能保存！");
                            return false;
                        } else {
                            that.verificationOnlyOne();
                        }
                    });
                } else {
                    that.saveEvent();
                }
            },
            //校验唯一性
            verificationOnlyOne() {
                const $table = this.$refs.xTable;
                const $tableData = $table.getTableData().tableData;
                const flowSeqs = [];
                $tableData.forEach(function (item) {
                    if (item.flowSeq) {
                        flowSeqs.push(item.flowSeq);
                    }
                });
                const newFlowSeqs = [...new Set(flowSeqs)];
                if (flowSeqs.length > newFlowSeqs.length) {
                    this.$XModal.alert("序号有重复值，不能保存！");
                    return false;
                }
                const upSerialNumbers = [];
                $tableData.forEach(function (item) {
                    if (item.upFlow) {
                        upSerialNumbers.push(item.upFlow);
                    }
                });
                const newUpSerialNumbers = [...new Set(upSerialNumbers)];
                if (upSerialNumbers.length > newUpSerialNumbers.length) {
                    this.$XModal.alert("上层序号有重复值，不能保存！");
                    return false;
                }
                this.saveEvent();
            },
            saveEvent() {
                const that = this;
                const tableData = this.tableData;
                const removeData = this.removeData.filter(function (item) {
                    return item.defaultIndex >= 0;
                });
                const isChangeSort = tableData.some(function (item, index) {
                    return item.defaultIndex >= 0 && item.defaultIndex !== index;
                });
                // const updateData = tableData.filter((item) => {
                const updateData = tableData.filter(function (item) {
                    return (
                        item.defaultIndex >= 0 &&
                        (item.nameT !== item.oldNameT ||
                            item.nameS !== item.oldNameS ||
                            item.chkUser !== item.oldChkUser ||
                            item.oldIsFirst !== item.isFirst ||
                            item.oldIsLast !== item.isLast)
                    );
                });
                const addData = tableData.filter(function (item) {
                    return !(item.defaultIndex >= 0);
                });
                console.log("removeData", removeData);
                console.log("updateData", updateData);
                that.$XModal.confirm("您确定要保存该数据?").then(async function (type) {
                    if (type === "confirm") {
                        that.loading = true;
                        if (isChangeSort) {
                            axios
                                .post("/baseStd/crud", tableData)
                                .then(function (response) {
                                    that.search();
                                    that.$message.success("保存成功");
                                })
                                .catch(function (error) {
                                    console.log(error);
                                    that.$message.error("保存异常");
                                    // }).finally(() => {
                                })
                                .finally(function () {
                                    that.loading = false;
                                });
                            return;
                        }
                        let flag = true;
                        if (removeData.length > 0) {
                            await axios
                                .post("/baseStd/delete", removeData)
                                .then(function (res) {
                                    that.removeData = [];
                                })
                                .catch((error) => {
                                    flag = false;
                                });
                        }
                        if (updateData.length > 0) {
                            await axios.post("/baseStd/update", updateData).catch((error) => {
                                flag = false;
                            });
                        }
                        if (addData.length > 0) {
                            await axios.post("/baseStd/add", addData).catch((error) => {
                                flag = false;
                            });
                        }
                        if (flag) {
                            that.$message.success("保存成功");
                        } else {
                            that.$message.error("保存异常");
                        }
                        that.search();
                        that.loading = false;
                    }
                });
            },
            zoomTable() {
                var t = window.devicePixelRatio; // 获取下载的缩放 125% -> 1.25    150% -> 1.5
                console.log("t", t);
                if (t > 1) {
                    // 如果进行了缩放，也就是不是1
                    let c = document.querySelector(".layui-layer");
                    // c.style.maxHeight="360px";   // 就去修改页面的缩放比例
                    c.style.zoom = 0.9;
                }
            },
        },
    });
</script>

<style>
    .layui-layer-shade {
        z-index: 999 !important;
    }

    .layui-layer {
        z-index: 1000 !important;
    }

    .w-app {
        display: flex;
        flex-direction: column;
        justify-content: center;
        text-align: center;
        font-size: 14px;
        padding: 0px 15px 15px 15px;
        background: #ffffff !important;
    }

    .text-center {
        text-align: center;
    }

    .text-left {
        text-align: left;
    }

    th,
    td {
        padding: 4px 4px;
    }

    .main-table,
    .main-table th,
    .main-table td {
        border-collapse: collapse;
        border: 1px solid #000;
    }

    .total > td {
        padding: 6px 4px;
    }

    .horizontal-sign {
        margin-top: 30px;
    }

    .sign {
        border-bottom: 1px solid #000;
        width: 200px;
    }

    .text-16px {
        font-size: 16px;
    }

    .wmarginleft30 {
        margin-left: 30px;
    }

    .layui-border-blue {
        color: rgb(30, 159, 255) !important;
    }

    .nameS-pulldown {
        min-width: 16em;
        padding: 0 1em;
        cursor: pointer;
    }

    .nameS-pulldown:hover {
        background-color: rgb(242, 242, 242);
    }
</style>

</html>